﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YasharEl.Infrastructure.WorkflowModel.Persistence.Extensions;

namespace YasharEl.Infrastructure.WorkflowModel.Activities.Persistance
{
    public class PromoteValueActivity<T> : CodeActivity
    {
        #region Properties

        public bool ClearExistingPromotedData { get; set; }
        public string Name { get; set; }

        [RequiredArgument]
        public InArgument<T> Value { get; set; }

        #endregion

        #region CodeActivity Overrides

        protected override void Execute(CodeActivityContext context)
        {
            GenericValuePromotionPersistenceExtension persistenceParticipant = 
                context.GetExtension<GenericValuePromotionPersistenceExtension>();

            if (persistenceParticipant != null && this.Name != null && this.Value != null)
            {
                if (this.ClearExistingPromotedData)
                {
                    persistenceParticipant.ClearExistingPromotionData();
                }

                string propertyName = this.Name;
                T propertyValue = context.GetValue<T>(this.Value);
                persistenceParticipant.AddPromotedVariable(propertyName, propertyValue);
            }
        }

        protected override void CacheMetadata(CodeActivityMetadata metadata)
        {
            metadata.RequireExtension<GenericValuePromotionPersistenceExtension>();
            base.CacheMetadata(metadata);
        }

        #endregion
    }
}
